package net.happy2v.file.server.test.file.factory;

import static org.jboss.netty.channel.Channels.pipeline;

import java.util.concurrent.Executors;

import net.happy2v.file.server.test.file.handler.TestHandler;
import net.ib.mn.protocol.CommonEnvelope.Envelope;
import net.ib.rpc.handler.RpcHandler;
import net.ib.rpc.method.MethodInfos;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder;
import org.jboss.netty.handler.execution.ExecutionHandler;

public class FileServerMainFactory implements ChannelPipelineFactory {

	private final MethodInfos localServices;
	private final MethodInfos remoteServices;

	public FileServerMainFactory(MethodInfos localServices) {
		this.localServices = localServices;
		this.remoteServices = new MethodInfos();
	}

	@Override
	public ChannelPipeline getPipeline() throws Exception {
		ChannelPipeline pipeline = pipeline();

		pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(
				1048576, 0, 4, 0, 4));
		pipeline.addLast("protobufDecoder",
				new ProtobufDecoder(Envelope.getDefaultInstance()));

		pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
		pipeline.addLast("protobufEncoder", new ProtobufEncoder());

		// ThreadPool 을 새로운 exeutor 로 넘겨 준다.
		pipeline.addLast("threadPoolHandler",
				new ExecutionHandler(Executors.newCachedThreadPool()));

		// 파이프 라인을 거치는 모든 데이터에 로그를 남긴다.
		pipeline.addLast("test", new TestHandler());

		pipeline.addLast("rpcHandler", new RpcHandler(localServices,
				remoteServices));
		return pipeline;
	}
}